package com.example.mobiletest.manager

import android.content.Context
import com.example.mobiletest.cache.BookingCache
import com.example.mobiletest.cache.BookingCacheImpl
import com.example.mobiletest.model.Booking
import com.example.mobiletest.service.BookingService
import com.example.mobiletest.service.BookingServiceImpl
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class BookingDataManager(context: Context) {
    
    private val bookingService: BookingService = BookingServiceImpl(context)
    private val bookingCache: BookingCache = BookingCacheImpl(context)
    
    // 使用StateFlow来向UI层提供响应式数据
    private val _bookingData = MutableStateFlow<Booking?>(null)
    val bookingData: StateFlow<Booking?> = _bookingData.asStateFlow()
    
    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
    
    private val _error = MutableStateFlow<String?>(null)
    val error: StateFlow<String?> = _error.asStateFlow()
    
    /**
     * 获取预订数据 - 优先从缓存获取，如果缓存无效则从网络获取
     */
    suspend fun getBookingData(): Booking? {
        println("BookingDataManager: Getting booking data...")
        _isLoading.value = true
        _error.value = null
        
        try {
            // 1. 首先检查缓存
            val cachedBooking = bookingCache.getBooking()
            if (cachedBooking != null && bookingCache.isCacheValid()) {
                println("BookingDataManager: Using cached data")
                _bookingData.value = cachedBooking
                return cachedBooking
            }
            
            // 2. 缓存无效，从网络获取
            println("BookingDataManager: Cache invalid, fetching from network...")
            val networkBooking = bookingService.getBookingData()
            
            if (networkBooking != null) {
                // 3. 保存到缓存
                bookingCache.saveBooking(networkBooking)
                _bookingData.value = networkBooking
                println("BookingDataManager: New data fetched and cached")
                
                // 打印详细的船只数据到控制台
                printBookingDetails(networkBooking)
                
                return networkBooking
            } else {
                // 4. 网络获取失败，尝试使用过期的缓存数据
                if (cachedBooking != null) {
                    println("BookingDataManager: Network failed, using expired cache data")
                    _bookingData.value = cachedBooking
                    _error.value = "数据可能不是最新的"
                    return cachedBooking
                } else {
                    _error.value = "无法获取预订数据"
                    return null
                }
            }
        } catch (e: Exception) {
            _error.value = "获取数据时发生错误: ${e.message}"
            println("BookingDataManager: Error - ${e.message}")
            return null
        } finally {
            _isLoading.value = false
        }
    }
    
    /**
     * 刷新预订数据 - 强制从网络获取最新数据
     */
    suspend fun refreshBookingData(): Booking? {
        println("BookingDataManager: Refreshing booking data...")
        _isLoading.value = true
        _error.value = null
        
        try {
            // 清除旧缓存
            bookingCache.clearCache()
            
            // 从网络获取新数据
            val newBooking = bookingService.refreshBookingData()
            
            if (newBooking != null) {
                // 保存新数据到缓存
                bookingCache.saveBooking(newBooking)
                _bookingData.value = newBooking
                println("BookingDataManager: Data refreshed successfully")
                
                // 打印详细的船只数据到控制台
                printBookingDetails(newBooking)
                
                return newBooking
            } else {
                _error.value = "刷新数据失败"
                return null
            }
        } catch (e: Exception) {
            _error.value = "刷新数据时发生错误: ${e.message}"
            println("BookingDataManager: Refresh error - ${e.message}")
            return null
        } finally {
            _isLoading.value = false
        }
    }
    
    /**
     * 清除所有数据和缓存
     */
    fun clearAllData() {
        bookingCache.clearCache()
        _bookingData.value = null
        _error.value = null
        println("BookingDataManager: All data cleared")
    }
    
    /**
     * 打印详细的船只预订信息到控制台
     */
    private fun printBookingDetails(booking: Booking) {
        println("========== 船只预订详细信息 ==========")
        println("船只参考号: ${booking.shipReference}")
        println("船只令牌: ${booking.shipToken}")
        println("可出票检查: ${booking.canIssueTicketChecking}")
        println("过期时间: ${booking.expiryTime}")
        println("持续时间: ${booking.duration}分钟")
        println("预订是否过期: ${if (booking.isBookingExpired()) "是" else "否"}")
        println("缓存时间: ${java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(java.util.Date(booking.cacheTime))}")
        
        println("\n航段信息 (共${booking.segments.size}个航段):")
        booking.segments.forEachIndexed { index, segment ->
            println("  航段 ${index + 1} (ID: ${segment.id}):")
            println("    出发地: ${segment.originAndDestinationPair.origin.displayName} (${segment.originAndDestinationPair.origin.code})")
            println("    出发城市: ${segment.originAndDestinationPair.originCity}")
            println("    目的地: ${segment.originAndDestinationPair.destination.displayName} (${segment.originAndDestinationPair.destination.code})")
            println("    目的城市: ${segment.originAndDestinationPair.destinationCity}")
            println("    官网: ${segment.originAndDestinationPair.origin.url}")
        }
        println("=====================================")
    }
}